1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| function debounceWithMaxWait(fn, delay = 2000, maxWait = 3000, leading = true) { let timer = null let lastTime = null let leadOpen = null return function () { let context = this let args = arguments
if (!lastTime) { lastTime = +new Date() }
let newTime = +new Date()
if(leading){ if (newTime - lastTime < maxWait) { if (!leadOpen) { leadOpen = true fn.apply(context, args) } else { clearTimeout(timer) } timer = setTimeout(() => { lastTime = null leadOpen = false }, delay) } else { lastTime = null leadOpen = false clearTimeout(timer) } }else { if (newTime - lastTime < maxWait) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { lastTime = null fn.apply(context, args) }, delay) } else { lastTime = null if (timer) { clearTimeout(timer) } fn.apply(context, args) } } } }
|